package com.bstek.uflo.designer.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.bstek.dorado.web.resolver.AbstractResolver;

/**
 * @author matt.yao@bstek.com
 * @since 1.0
 */
public class DownloadFileResolver extends AbstractResolver {

	@Override
	protected ModelAndView doHandleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		doDownloadFile(request, response);
		return null;
	}

	private void doDownloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String key = request.getParameter("key");
		if (!StringUtils.hasText(key)) {
			printError(response);
			return;
		}
		String filePath = FileKeyManager.getFileKey(key);
		if (!StringUtils.hasText(filePath)) {
			printError(response);
			return;
		}
		File file = null;
		try {
			file = new File(filePath);
		} catch (Exception e1) {
			printError(response);
			return;
		}
		FileInputStream input = null;
		OutputStream output = null;
		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "No-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("application/octet-stream;charset=utf-8");
			String fileName = "process.uflo.xml";
			response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
			input = new FileInputStream(file);
			output = response.getOutputStream();
			IOUtils.copy(input, output);
			output.flush();
		} catch (Exception e) {
			printError(response);
		} finally {
			IOUtils.closeQuietly(input);
			IOUtils.closeQuietly(output);
		}
	}

	private void printError(HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.print(" Request is illegal !");
		writer.flush();
		writer.close();
	}
}
